from django import forms
from django.core.exceptions import ValidationError
from chart_web import models


class poet_password(forms.Form):
    '''poet form'''
    group = forms.CharField(
        min_length=6,  # 设置最小长度
        max_length=225,  # 设置最大长度
        label="组名",  # 设置标签名
        # 错误信息提示设置
        error_messages={
            "min_length": "组名不能少于6位",
            "max_length": '组名不能超过225位',
            "required": "组名不能为空"
        },
        # 插件设置
        widget=forms.widgets.TextInput(
            attrs={"class": "form-control"}  # 给生成的标签添加属性 form-control-- bootstrap样式
        )
    )

    def __init__(self, request, *args, **kwargs):
        super(poet_password, self).__init__(*args, **kwargs)
        self.request = request

    def clean(self):
        # 判断当前密码是否为数字
        group = self.cleaned_data.get('group')
        if group and group.isdigit():
            # 查询当前group是否有人创建
            group_obj = models.Group.objects.filter(group=group).first()
            if not group_obj:
                # 没有，为创建者
                models.Group.objects.create(
                    group=group,
                    userinfo=self.request.chart_web.user
                )
            else:
                # 有，为群员
                models.Group.objects.create(
                    group=group,
                    userinfo=group_obj.userinfo,
                    join_user=self.request.chart_web.user.username
                )
        else:
            raise ValidationError('组名不能为空，必须是6位以上的数字！！！')
